package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.minio.MinIOTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class CreateHtmlTask {

    @Autowired
    private IApArticleService apArticleService;
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinIOTemplate minIOTemplate;

    @Async
    public void createHtml(ApArticle apArticle,String content){
        try {
            Long articleId = apArticle.getId();

            //准备数据
            List<Map> mapList = JSON.parseArray(content, Map.class);
            Map dataModel = new HashMap();
            dataModel.put("content",mapList);

            //获取模板
            Template template = configuration.getTemplate("article.ftl");

            //数据和模板结合
            StringWriter writer = new StringWriter();
            template.process(dataModel,writer);

            //把生成的html放到minio上
            InputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            minIOTemplate.upload("/article/"+articleId+".html",inputStream,"text/html")  ;// String name, InputStream inputStream, String contentType


            //http://192.168.85.143:9000/heima

            //ApArticle apArticle = apArticleService.getById(articleId);
            apArticle.setStaticUrl("http://192.168.85.143:9000/heima/"+articleId+".html");
            apArticleService.updateById(apArticle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
